package org.foj.model {
import flash.events.EventDispatcher;

import mx.messaging.ChannelSet;
import mx.messaging.Consumer;
import mx.messaging.events.MessageEvent;
import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;
import mx.rpc.soap.WebService;

import org.foj.dto.Issue;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.UIEvent;

public class IssueModel {

    private var _issueService:RemoteObject;

    public function IssueModel() {
        _issueService = new RemoteObject();
//        _issueService.wsdl =
//                "http://localhost:8080/services/IssueService?wsdl";
       var defaultChannelSet:ChannelSet = ChannelSetFactory.getDefaultChannel();

      _issueService.destination = "issueService";
      _issueService.channelSet = defaultChannelSet;
/*        if (_issueService.canLoadWSDL()) {
            _issueService.loadWSDL();
        }*/
        var messageChannelSet:ChannelSet = ChannelSetFactory.getMessagingChannel();
        var consumer:Consumer = new Consumer();
        consumer.destination = "flexMessage";
        consumer.channelSet = messageChannelSet;
        consumer.addEventListener(MessageEvent.MESSAGE, messageHandler);
        consumer.subscribe();
    }

    private function messageHandler(event:MessageEvent):void {
        var eventDispatcher:EventDispatcher = EventDispatcherFactory.getEventDispatcher();
        var refreshEvent:UIEvent = new UIEvent(UIEvent.REFRESH_ISSUES_BUTTON_CLICKED);
        eventDispatcher.dispatchEvent(refreshEvent);
    }

    public function getIssues(responder:IResponder):void {
        var token:AsyncToken = _issueService.getAll();
        token.addResponder(responder);
    }
    public function removeIssue(id:Number, responder:IResponder):void {
        var token:AsyncToken = _issueService.remove(id);
        token.addResponder(responder);
    }
    public function getIssue(id:Number, responder:IResponder):void {
        var token:AsyncToken = _issueService.get(id);
        token.addResponder(responder);
    }
    public function saveIssue(issue:Issue, responder:IResponder):void {
        var token:AsyncToken = _issueService.save(issue);
        token.addResponder(responder);
    }
}
}
